<template>
  <div style="height: 100%">
    <a-spin :spinning="isTableLoading" wrapperClassName="spinning-container">
      <div class="header-container" ref="headerContainer">
        <page-header :title="l('Notifications')"></page-header>
        <!-- 表格部分 -->
        <a-card :border="false">
          <div class="mb-md" style="float: right">
            <!-- 操作按钮 -->
            <a-row nzGutter="8">
              <!-- 添加、批量删除、导出Excel表等按钮 -->
              <a-col nzMd="20" nzSm="12" class="btn-gutter">
                <a-button
                  :type="'primary'"
                  v-if="isGranted('Pages.Administration.Roles.Create')"
                  @click="setAllUserNotificationsAsRead()"
                >
                  <link-outlined />
                  <span>
                    {{ l('SetAllAsRead') }}
                  </span>
                </a-button>
              </a-col>
            </a-row>
          </div>
          <!-- 检索的表单内容 -->
          <a-form :model="form" :layout="'vertical'" @submit="refreshGoFirstPage()" class="mb-md">
            <!-- 模糊搜索框 -->
            <a-row :gutter="24">
              <a-col :sm="4">
                <a-form-item name="startTime" :label="l('StartTime')">
                  <a-form-control>
                    <a-date-picker
                      showTime
                      style="width: 100%"
                      v-model:value="startDate"
                      name="startTime"
                      :placeholder="l('PleaseSelectDate')"
                    />
                  </a-form-control>
                </a-form-item>
              </a-col>
              <a-col :sm="4">
                <a-form-item name="endTime" :label="l('EndTime')">
                  <a-form-control>
                    <a-date-picker
                      showTime
                      style="width: 100%"
                      v-model:value="endDate"
                      name="endTime"
                      :placeholder="l('PleaseSelectDate')"
                    />
                  </a-form-control>
                </a-form-item>
              </a-col>
              <a-col :sm="4">
                <a-form-item name="readState" :label="l('NotificationStates')">
                  <a-form-control>
                    <a-select
                      name="readState"
                      style="width: 100%"
                      v-model:value="form.state"
                      :placeholder="l('NotificationStates')"
                      :allowClear="true"
                    >
                      <a-select-option
                        v-for="item in stateList"
                        :value="item.value"
                        :key="item.key"
                      >
                        {{ item.key }}
                      </a-select-option>
                    </a-select>
                  </a-form-control>
                </a-form-item>
              </a-col>
              <a-col :sm="4" class="btn-gutter">
                <a-form-item name="readState" :colon="false" label=" ">
                  <a-form-control>
                    <a-button type="primary" @click="query()">{{ l('Query') }}</a-button>
                  </a-form-control>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <!-- 数据部分 -->
          <!-- <div class="my-md">
          <a-alert :type="'info'" :showIcon="true">
            <template #message>
              <a @click="refresh()" class="ml-md">
                {{ l('Refresh') }}
              </a>
            </template>
          </a-alert>
        </div> -->
        </a-card>
        <a-card>
          <div class="table-container">
            <a-table
              size="middle"
              :scroll="{ x: tableWidthScroll, y: tableHeightScroll }"
              :columns="columns"
              :data-source="dataList"
              :pagination="{
                total: totalItems,
                current: pageNumber,
                pageSize: pageSize,
                showTotal: showTotalInfo,
                showQuickJumper: true,
                showSizeChanger: true,
                change: pageNumberChange,
                showSizeChange: pageNumberChange,
                pageSizeOptions: pageSizeOptions,
                size: 'middle',
              }"
              @change="tableChange"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'notstate'">
                  <a-tag color="red" v-if="record.state === 'UNREAD'">{{ l(record.state) }}</a-tag>
                  <a-tag color="green" v-if="record.state !== 'UNREAD'">{{
                    l(record.state)
                  }}</a-tag>
                </template>
                <template v-if="column.key === 'actions'">
                  <!-- 修改 -->
                  <a @click="setAsRead(record)" v-if="record.state == 'UNREAD'">
                    <edit-outlined />
                    <span>{{ l('SetAsRead') }}</span>
                    <a-divider type="vertical" />
                  </a>
                  <!-- 删除 -->
                  <a-popconfirm
                    placement="top"
                    :okText="l('Ok')"
                    v-if="record.state !== 'UNREAD'"
                    :cancelText="l('Cancel')"
                    @confirm="deleteItem(record)"
                  >
                    <template #title>{{ l('ConfirmDeleteWarningMessage') }}</template>
                    <a>
                      <delete-outlined />
                      <span>{{ l('Delete') }}</span>
                      <a-divider type="vertical" />
                    </a>
                  </a-popconfirm>
                </template>
              </template>
            </a-table>
          </div>
        </a-card>
      </div>
      <!-- 表格 -->
    </a-spin>
  </div>
</template>
<script lang="ts">
  import {
    GetUserNotificationsInput,
    NotificationServiceProxy,
    UserNotification,
  } from '/@/shared/service-proxies/service-proxies';
  import { AppUserNotificationState } from '/@/abpPro/AppEnums';
  import { IFormattedUserNotification } from '/@/shared/helpers/UserNotificationHelper';
  import userNotificationHelper from '/@/shared/helpers/UserNotificationHelper';
  import { PagedListingComponentBase } from '/@/shared/component-base';
  import { LinkOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
  import { defineComponent } from 'vue';
  import { IPagedRequestDto } from '/@/shared/component-base/interfaces';
  import { ColumnType } from 'ant-design-vue/lib/table';
  export default defineComponent({
    name: 'notifications',
    components: {
      LinkOutlined,
      DeleteOutlined,
      EditOutlined,
    },
    mixins: [PagedListingComponentBase],
    data() {
      return {
        form: {
          state: undefined,
        },
        columns: [],
        stateList: [
          { key: this.l('NotificationRead'), value: AppUserNotificationState.Read },
          { key: this.l('NotificationUnread'), value: AppUserNotificationState.Unread },
        ],
        dataList: [] as IFormattedUserNotification[],
        notificationService: new NotificationServiceProxy(),
        userNotificationHelper: userNotificationHelper,
        fetchinput: new GetUserNotificationsInput(),
        pag: PagedListingComponentBase,
        startDate: '',
        endDate: '',
      };
    },
    created() {
      this.notificationService = new NotificationServiceProxy(this.$apiUrl, this.$api);
      this.userNotificationHelper.init();
    },
    methods: {
      // 获取列配置
      getColumns(): ColumnType<UserNotification>[] {
        return [
          {
            title: 'No',
            customRender: ({ index }) => {
              const a = (this.pageNumber - 1) * this.pageSize + (index + 1);
              return a;
            },
            width: 60,
            fixed: 'left',
          },
          {
            title: this.l('NotificationContent'),
            dataIndex: 'text',
            key: 'text',
            ellipsis: true,
          },
          {
            title: this.l('CreationTime'),
            dataIndex: 'time',
            key: 'time',
            ellipsis: true,
          },
          {
            title: this.l('NotificationStates'),
            dataIndex: 'notstate',
            key: 'notstate',
            ellipsis: true,
            width: 250,
          },
          {
            title: this.l('Actions'),
            dataIndex: 'actions',
            key: 'actions',
            width: 180,
            align: 'center',
            ellipsis: true,
            fixed: 'right',
          },
        ];
      },
      // 获取数据
      fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
        if (this.startDate) {
          this.fetchinput.startTime = (this.startDate as any).add(8, 'h');
        }
        if (this.endDate) {
          this.fetchinput.endTime = (this.endDate as any).add(8, 'h');
        }
        this.fetchinput.state = this.form.state as any;
        this.fetchinput.maxResultCount = request.maxResultCount;
        this.fetchinput.skipCount = request.skipCount;
        this.notificationService
          .getPagedUserNotifications(this.fetchinput)
          .finally(() => {
            finishedCallback!();
          })
          .then((res) => {
            this.showPaging(res);
            this.dataList = this.formatNotifications(res.items as any);
            // this.dataList = this.formatNotifications(res.items as any).map(
            //   (item) => item.formattedNotification,
            // );
            console.log(this.dataList);
          });
      },
      query() {
        this.pageNumber = 1;
        this.refresh();
      },
      setAsRead(item: IFormattedUserNotification) {
        this.userNotificationHelper.setAsRead(item.userNotificationId, () => {
          this.refresh();
        });
      },
      deleteItem(item: UserNotification) {
        this.notificationService.deleteNotification(item.id).then(() => {
          this.notify.success(this.l('SuccessfullyDeleted'));
          this.refreshGoFirstPage();
        });
      },
      setAllUserNotificationsAsRead() {
        this.userNotificationHelper.setAllAsRead();
        this.refresh();
      },
      formatNotifications(records: any[]): IFormattedUserNotification[] {
        const formattedRecords: IFormattedUserNotification[] = [];
        for (const record of records) {
          record.formattedNotification = this.formatRecord(record);
          formattedRecords.push(record as never);
        }
        return formattedRecords;
      },
      formatRecord(record: any): IFormattedUserNotification {
        return this.userNotificationHelper.format(record, false);
      },
    },
  });
</script>
